package com.ma.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ma.auth.service.SysMenuService;
import com.ma.auth.service.SysUserService;
import com.ma.model.system.SysUser;
import com.ma.security.custom.CustomUser;
import com.ma.security.custom.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if (null == sysUser){
            throw new UsernameNotFoundException("用户不存在！");
        }
        if (sysUser.getStatus() == 0){
            throw new RuntimeException("账号已经停用");
        }
        //根据用户id查询用户操作权限数据
        List<String> permsList = sysMenuService.findUserPermsByUserId(sysUser.getId());
        //创建List集合，用来封装最终权限数据
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        for (String perm : permsList){
            authorityList.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new CustomUser(sysUser, authorityList);
    }
}
